package com.aspire.boc.mms.wmf.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aspire.boc.mms.wmf.cam.Admin;
import com.aspire.boc.mms.wmf.model.Ext4JsTreeNode;
import com.aspire.boc.mms.wmf.model.ExtJsTreeNode;
import com.aspire.boc.mms.wmf.model.SecurityUser;
import com.aspire.boc.mms.wmf.model.WmfAction;
import com.aspire.boc.mms.wmf.model.WmfResource;
import com.aspire.boc.mms.wmf.permission.PermissionCacheService;
import com.aspire.boc.mms.wmf.service.PermissionService;
import com.aspire.boc.mms.wmf.util.ResourceTreeUtil;

/**
 * 资源控制
 * @author chenjianjun
 * @date 2013-5-17 上午11:11:16
 */
@Controller
public class ResourceAct {
	private static Log log = LogFactory.getLog(ResourceAct.class);
	
	@RequestMapping(value = "/resource/index")
	public String index(HttpServletRequest request, HttpServletResponse response ,HttpSession session) {
		return "../views/wmf/resource/index.jsp";
	}
	
	/**
	 * 加载授权菜单树
	 * @param roleId 角色编号
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/resource/loadAuthResourceTree", produces = {"text/javascript;;charset=UTF-8"} )
	@ResponseBody
	public String loadAuthResourceTree(@RequestParam(value = "roleId", required = true) String roleId,
			HttpServletRequest request, HttpServletResponse response) {
		
		log.info(">>>>> operation: /resource/loadAuthResourceTree, params:[roleId: "+roleId+"]");
		// 获取授权actionId集合
		List<Integer> authActionIds = permissionService.getActionsByRole(Arrays.asList(new String[]{roleId}));
		if(authActionIds == null) {
			log.error(">>>>> operation: /resource/loadAuthResourceTree, result: no authorized action id[authActionIds="+authActionIds+"]");
			return "{}";
		}
		// 获取授权resourceId集合
		List<Integer> authResourceIds = new ArrayList<Integer>();
		for(WmfResource resource : permissionCacheService.getAuthorizedResources(authActionIds)){
			authResourceIds.add(resource.getId());
		}
		
		Map<Integer, WmfResource> allResourceCacheMap = permissionCacheService.getResourceCacheMap();
		if(allResourceCacheMap == null) {
			log.error(">>>>> operation: /resource/loadAuthResourceTree, result: no authorized resource id[allResourceCacheMap="+allResourceCacheMap+"]");
			return "{}";
		}
		Map<Integer, Ext4JsTreeNode> allTreeNodeMap = new HashMap<Integer, Ext4JsTreeNode>();
		Ext4JsTreeNode rootTreeNode = new Ext4JsTreeNode();
		rootTreeNode.setResourceId(0);
		allTreeNodeMap.put(new Integer(0), rootTreeNode);
		for(Entry<Integer, WmfResource> resourceItem : allResourceCacheMap.entrySet()) {
			Integer resourceId = resourceItem.getKey();
			Ext4JsTreeNode treeNode = convertResource2Ext4jsTreeNode(resourceItem.getValue());
			if(authResourceIds.contains(resourceId)) {
				treeNode.setChecked(true);
			}
			allTreeNodeMap.put(resourceId, treeNode);
		}
		Collection<Ext4JsTreeNode> allTreeNodeCollection = allTreeNodeMap.values();
		List<Ext4JsTreeNode> allTreeNodeList = new ArrayList<Ext4JsTreeNode>(allTreeNodeCollection.size());
		allTreeNodeList.addAll(allTreeNodeCollection);
		
		String jsonTree = ResourceTreeUtil.assembleExt4JsTree(allTreeNodeList, 0).toString();
		log.info(">>>>> operation: /resource/loadAuthResourceTree, params:[roleId: "+roleId+"], success to get resource tree string: " + jsonTree);
		return jsonTree;
	}
	
	@RequestMapping(value = "/resource/loadRoleResourceTree")
	public @ResponseBody List<ExtJsTreeNode> loadRoleResourceTree(
			@RequestParam(value = "roleId", required = false) final String roleId,
			@RequestParam(value = "node", required = false) final String pid,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		log.info(">>>>>>>>  /resource/loadRoleResourceTree ----> roleId  --->" + roleId);
		@SuppressWarnings("serial")
		List<Integer> acitonsIntegers = permissionService.getActionsByRole( new ArrayList<String>() {{ add(roleId);}} );
		//根据角色获取已经有的资源
		Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
		for(WmfResource resource : permissionCacheService.getResourcesActionId(acitonsIntegers)){
			map.put(resource.getId(),true);
		}
		//根据角色获取资源树
		SecurityUser securityUser = (SecurityUser) request.getSession().getAttribute("securityUser");
		boolean isAdministrator = securityUser.isSystemAdmin();
		List<WmfResource> resourceList = permissionCacheService.getResourcesPid(pid,isAdministrator);
		List<ExtJsTreeNode> nodes = new ArrayList<ExtJsTreeNode>();
		for (WmfResource resource : resourceList) {
			ExtJsTreeNode node = new ExtJsTreeNode();
			node.setId(String.valueOf(resource.getId()));
			node.setPID(pid);
			node.setIsRoot(false);
			node.setText(resource.getName() + "(" + resource.getId() + ")");
			node.setEnname(resource.getEnname());
			node.setQtip(resource.getName());
			node.setExpanded(true);
			node.setExt1(resource.getName());
			//是否被选择
			if(null != map.get(resource.getId()) && map.get(resource.getId())){
				node.setChecked(true);
			}else{
				node.setChecked(false);
			}
			nodes.add(node);
		}
		return nodes;
	}
	
	@RequestMapping(value = "/resource/loadResourceTree")
	public @ResponseBody List<ExtJsTreeNode> loadResourceTree(
			@RequestParam(value = "roleId", required = false) final String roleId,
			@RequestParam(value = "node", required = false) final String pid,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		log.info(">>>>>>>>  /resource/loadRoleResourceTree   --->" );
		//根据角色获取资源树
		SecurityUser securityUser = (SecurityUser) request.getSession().getAttribute("securityUser");
		boolean isAdmin = securityUser.isSystemAdmin();
		List<WmfResource> resourceList = permissionCacheService.getResourcesPid(pid,isAdmin);
		List<ExtJsTreeNode> nodes = new ArrayList<ExtJsTreeNode>();
		for (WmfResource resource : resourceList) {
			ExtJsTreeNode node = new ExtJsTreeNode();
			node.setId(String.valueOf(resource.getId()));
			node.setPID(pid);
			node.setIsRoot(false);
			node.setText(resource.getName() + "(" + resource.getId() + ")");
			node.setEnname(resource.getEnname());
			node.setQtip(resource.getName());
			node.setExpanded(resource.getIsleaf().equals("N") ? false : true);
			node.setExt1(resource.getName());
			nodes.add(node);
		}
		return nodes;
	}
	
	/**
	 * 
	 * @Title: loadResourceTreeActions 
	 * @Description: TODO(加载资源树下功能按钮列表，2以内按钮即可) 
	 * @param resourceid
	 * @param roleId
	 * @param ownertype
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/resource/loadActionsResourceId")
	public @ResponseBody Map<String, List<WmfAction>> loadResourceTreeActions(
			@RequestParam(value = "clickResourceId", required = false) String resourceid,
			HttpServletRequest request,
			HttpServletResponse response){
		log.info(">>>>>>  access /resource/loadActionsResourceId,parm:(resourceid=" + resourceid + ")");
		//获取选中资源
		
		Map<String, List<WmfAction>> roleAuths = new HashMap<String, List<WmfAction>>();
		List<WmfAction> actions = new ArrayList<WmfAction>();
		if(resourceid != null && !"".equals(resourceid)){
			actions = permissionCacheService.getActionsResourceId(new Integer(resourceid),"1,2");
		}
		roleAuths.put("actions", actions);
		return roleAuths;
	}
	
	/**
	 * WfmResource -> Ext4jsTreeNode
	 * @param resource
	 * @return
	 */
	private Ext4JsTreeNode convertResource2Ext4jsTreeNode(WmfResource resource) {
		
		Ext4JsTreeNode treeNode = new Ext4JsTreeNode();
		treeNode.setResourceId(resource.getId());
		treeNode.setText(resource.getName());
		treeNode.setExpanded("Y".equals(resource.getIsopen()) ? true : false);
		treeNode.setLeaf("Y".equals(resource.getIsleaf()) ? true : false);
		treeNode.setParentResourceId(resource.getParentid().intValue());
		treeNode.setIconCls(resource.getIcon());
		return treeNode;
	}
	
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private PermissionCacheService permissionCacheService;
}
	
	
